package thread;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/27
 * Time:19:20
 * 使用全局自定义变量来终止线程
 **/
public class ThreadDemo11 {
    private static boolean flag = false;

    public static void main(String[] args) throws InterruptedException {
        //转账线程
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!flag) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("正在转账");
                }
                System.out.println("终止转账");//当flag为true走到这
            }
        });
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(310);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //改变变量的状态来中宗线程执行
                System.out.println("有内鬼，终止交易");
                flag = true;
            }
        });
        t2.start();

        t1.join();
        t2.join();
    }
}
